#!/usr/bin/env bash

#$1,daf path
#$2,proto file output directory

complie_proto_cur_dir=`pwd`

proto_home=$1
proto_gen_dir=$2

if [ $# -ne 2 ]; then
    echo "-- error,this script can not be executed by hand."
    echo "-- error,need 2 parameters,exist."
    exit 1
fi

if [ ! -d $proto_home ]; then
    echo "-- error,$proto_home does not exist."
    exit 1
fi

if [ ! -d $proto_gen_dir ]; then
    mkdir -p $proto_gen_dir
fi

#$1,make dir of 1 parameter as same level directory
mkdir_tmp()
{
    mkdir_tmp_cur_dir=`pwd`

    cd $1
    cur_1=`pwd`
    dir_base=`basename $cur_1`
    dir_name=`dirname $cur_1`
    unset cur_1
    tmp_path=${dir_name}/${dir_base}_tmp

    if [ ! -d $tmp_path ];then
        mkdir -p $tmp_path
    fi

    printf "$tmp_path" #return tmp path
    cd $mkdir_tmp_cur_dir
    unset mkdir_tmp_cur_dir
}

proto_gen_dir_tmp=`mkdir_tmp $proto_gen_dir`

proto_dirs=(
#$daf_path/proto
#$daf_path/src/communication/lib/messages
#$daf_path/src/status/ZSmartAgent/proto
$proto_home/proto
)

#if [ -d $HOME/git/status/ZSmartAgent/proto ];then
#    proto_dirs=(${proto_dirs[@]} 
#    $HOME/git/status/ZSmartAgent/proto
#    )
#fi

rm -f $proto_gen_dir_tmp/*

for proto_dir in ${proto_dirs[*]} ; do
    if [ -d ${proto_dir} ] ; then
        protoc --cpp_out=$proto_gen_dir_tmp -I=${proto_dir} ${proto_dir}/*.proto
    fi
done

#rm invalide old file
for each_file in `ls $proto_gen_dir` ;
do
    if [ ! -f $proto_gen_dir_tmp/$each_file ];then
        rm -f $proto_gen_dir/$each_file
    fi
done

for each_file in `ls $proto_gen_dir_tmp` ;
do
    if [ ! -f $proto_gen_dir/$each_file ];then
        cp $proto_gen_dir_tmp/$each_file $proto_gen_dir/$each_file
    else
        diff $proto_gen_dir_tmp/$each_file $proto_gen_dir/$each_file > /dev/null
        if [ $? -ne 0 ]; then
            cp $proto_gen_dir_tmp/$each_file $proto_gen_dir/$each_file
        fi
 
    fi
done






